package com.cuotigou.service.impl;

import com.cuotigou.config.ConfigUtils;
import com.cuotigou.mapper.*;
import com.cuotigou.pojo.MobileCode;
import com.cuotigou.pojo.SGrade;
import com.cuotigou.pojo.SRechargeList;
import com.cuotigou.pojo.SUser;
import com.cuotigou.service.UserService;
import com.cuotigou.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/31.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SGradeMapper sGradeMapper;
    @Autowired
    private SMobileCodeMapper sMobileCodeMapper;
    @Autowired
    private SRechargeListMapper sRechargeListMapper;
    @Autowired
    private SConfigMapper sConfigMapper;

    @Override
    public ObjectResult register(XMLBean xmlBean) {
        MobileCode mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());

        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser sUser = sUserMapper.selectUserByMap(map);
        if (sUser!=null){
            return ObjectResult.build("0","该用户已注册");
        }
        if (xmlBean.getPassword().length()<6){
            return  ObjectResult.build("0 ","密码不能低于六位");
        }
        try {
            String salt = RandomUtil.getRandom(6);
            //md5加密
            String password = CommonUtils.getMD5(xmlBean.getPassword()+salt);
            SGrade sGrade = sGradeMapper.selectGradeBygrade(xmlBean.getGrade());

            //添加用户表
            SUser user1 = new SUser();
            user1.setMobile(xmlBean.getMobile());
            user1.setPassword(password);
            user1.setUsername(xmlBean.getUsername());
            user1.setGrade(xmlBean.getGrade());
            user1.setGradeId(sGrade.getId());
            user1.setCity(xmlBean.getCity());
            user1.setAddTime(new Date());
            user1.setSalt(salt);
            sUserMapper.insertSelective(user1);
            //生成token
            String token =CommonUtils.createToken(user1.getMobile(),user1.getPassword(),user1.getId(),user1.getUsername());

            map.clear();
            map.put("mobile",user1.getMobile());
            map.put("username",user1.getUsername());
            map.put("grade",user1.getGrade());
            map.put("city",user1.getCity());
            map.put("integral",user1.getIntegral());
            map.put("school",user1.getSchool());
            map.put("sex",user1.getSex());
            map.put("token",token);
            return ObjectResult.build("1","注册成功",map);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","注册失败");
        }
    }

    @Override
    public ObjectResult login(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser user = sUserMapper.selectUserByMap(map);
        if (user!=null && user.getPassword().equals(CommonUtils.getMD5(xmlBean.getPassword()+user.getSalt()))){

            //返回数据
            String token =CommonUtils.createToken(user.getMobile(),user.getPassword(),user.getId(),user.getUsername());
            map.clear();
            map.put("mobile",user.getMobile());
            map.put("username",user.getUsername());
            map.put("grade",user.getGrade());
            map.put("city",user.getCity());
            map.put("integral",user.getIntegral());
            map.put("school",user.getSchool());
             map.put("sex",user.getSex());
            map.put("isVip",user.getIsVip());
            map.put("token",token);
            return ObjectResult.build("1","登陆成功",map);
        }else {
            return ObjectResult.build("0","用户名或密码错误");
        }
    }

    @Override
    public ObjectResult updatePassword(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser user = sUserMapper.selectUserByMap(map);
        if (user==null){
            return ObjectResult.build("0","未注册的用户");
        }
        try {
            if (xmlBean.getPassword().length()<6){
                return  ObjectResult.build("0 ","密码不能低于六位");
            }
            //md5加密
            String password = CommonUtils.getMD5(xmlBean.getPassword()+user.getSalt());
            if (user.getPassword().equals(password)){
                return  ObjectResult.build("0 ","不能与原密码相同");
            }
            user.setPassword(password);
            sUserMapper.updateByPrimaryKeySelective(user);
            return ObjectResult.build("1","修改密码成功");
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","修改密码失败");
        }
    }

    @Override
    public ObjectResult updateInform(XMLBean xmlBean,HttpServletRequest request) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser1 = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));
        String head = request.getParameter("head");

        if (!sUser1.getUsername().equals(xmlBean.getUsername())){
            Map<String,Object> map = new HashMap<>();
            map.put("username",xmlBean.getUsername());
            SUser user = sUserMapper.selectUserByMap(map);
            if (user != null){
                return ObjectResult.build("0","该昵称已被使用");
            }
        }
        try {
            SUser sUser = new SUser();
            //修改头像
            if (!StringUtil.isEmpty(head)){
                String imageName = ImageUploadUtil.uploadBaseImg(ConfigUtils.HEAD_URL, head);
                sUser.setHead(ConfigUtils.FILE_URL+"image/head/"+imageName);

            }
            //查询年级
            SGrade sGrade = sGradeMapper.selectGradeBygrade(xmlBean.getGrade().trim());

            //修改个人信息
            sUser.setId(Long.parseLong(userId));
            sUser.setUsername(xmlBean.getUsername());
            sUser.setSex(xmlBean.getSex());
            sUser.setCity(xmlBean.getCity());
            sUser.setSchool(xmlBean.getSchool());
            sUser.setGrade(xmlBean.getGrade());
            sUser.setGradeId(sGrade.getId());
            sUserMapper.updateByPrimaryKeySelective(sUser);
            return ObjectResult.build("1","修改个人信息成功");
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","修改个人信息失败，请联系客服");
        }
    }

    @Override
    public ObjectResult vip(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

        //会员剩余天数
        int day = 0;
        if(sUser.getExpireTime()!=null){
            if(DateUtil.getDaysBetweenToDate(sUser.getExpireTime(), new Date())>0){
                day = DateUtil.getDaysBetweenToDate(sUser.getExpireTime(), new Date());
            }else {
                sUser.setIsVip(0);
                sUserMapper.updateByPrimaryKeySelective(sUser);
            }

        }

        List<SRechargeList> list = sRechargeListMapper.selectByType(1);
        for (SRechargeList sRechargeList:list){
            sRechargeList.setCost(sRechargeList.getCost());
        }

        String not_vip = sConfigMapper.select("not_vip");

        Map<String,Object> map = new HashMap<>();
        map.put("day",day);
        map.put("list",list);
        map.put("isVip",sUser.getIsVip());
        map.put("notVip","非会员可导入管理"+not_vip+"道错题,会员则无数量限制且可查看和下载打印类似习题");
        return ObjectResult.build("1","成功",map);
    }
}
